package com.demo.OtherTest.TestDistance;

import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GeodeticCalculator;
import org.gavaghan.geodesy.GlobalCoordinates;

import java.math.BigDecimal;

public class DistanceUtil {
//温馨提示这是2个点A(经度，维度)，B（经度，维度），不是四个别犯迷糊
    public static void main(String[] args) {
//        System.out.println("经纬度距离计算结果：" + getDistance(121.07398513720135,32.10245478915197, 121.07399547289714,31.10243919141623) + "米");
        System.out.println(getDistance1(27.861153555555553,121.06941499999999,27.961637,121.069305)  + "米");
    }

    /*public static double getDistance(double longitudeFrom, double latitudeFrom, double longitudeTo, double latitudeTo) {
        GlobalCoordinates source = new GlobalCoordinates(latitudeFrom, longitudeFrom);
        GlobalCoordinates target = new GlobalCoordinates(latitudeTo, longitudeTo);

        return new GeodeticCalculator().calculateGeodeticCurve(Ellipsoid.Sphere, source, target).getEllipsoidalDistance();
    }*/



    private static double getDistance1(Double lat1, Double lng1, Double lat2, Double lng2) {
        // 存在null值，无法计算，返回 NULL_DISTANCE 99999.99
        if (null == lat1 || null == lng1 || null == lat2 || null == lng2) {
            return 0.0;
        }
        double radLat1 = getRadian(lat1);
        double radLat2 = getRadian(lat2);
        double a = radLat1 - radLat2;// 两点纬度差
        double b = getRadian(lng1) - getRadian(lng2);// 两点的经度差
        double distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                Math.cos(radLat1)* Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));

        return new BigDecimal(distance * 6378.137).setScale(9, BigDecimal.ROUND_HALF_UP).doubleValue();
//        return distance;
    }
    private static double getRadian(double degree) {
        return degree * Math.PI / 180.0;
    }
}

